package com.bjpowernode.task;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.mvc.service.inter.IncomeService;
import com.bjpowernode.pay.service.PayService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class TaskManager {

  /*  //定时任务的方法
    @Scheduled(cron ="0/5 * * * * ?" )
    public void testTask(){
        System.out.println("定时任务."+new Date());
    }*/

    //生成收益计划.
    @Resource
    private IncomeService incomeService;
    @Resource
    private PayService payService;
    @Scheduled(cron = "0 0 1 * * ?")   //每天凌晨一点执行
    public void taskIncomePlan(){
        incomeService.generateIncomePlan();
    }

    //收益返还.
    @Scheduled(cron = "0 0 2 * * ?")   //每天凌晨2点执行
    public void taskIncomeBack(){
        incomeService.generateIncomeBack();
    }



    //定时任务,调用快钱的查询接口
    @Scheduled(cron = "0 0/20 * * * ?")
    public void taskExecQuery(){
        //从redis获取订单号
        Set<ZSetOperations.TypedTuple<String>> orderSets= payService.getOrderIdFromRedis();
        for (ZSetOperations.TypedTuple<String> el : orderSets) {
            String orderId=el.getValue();

            //调用查询接口.
          String json=  payService.executeQueryOrder(orderId);


          //处理json格式的返回结果
            JSONObject queryResulyObject = JSONUtil.parseObj(json);
            JSONArray orderDetail = queryResulyObject.getJSONArray("orderDetail");
            /*if (JSONUtil.isNull(orderDetail)){
                System.out.println("查询结果是null");
            }else {
                System.out.println("查询有订单数据");
            }*/
            if(!JSONUtil.isNull(orderDetail)){
                JSONObject detail =(JSONObject) orderDetail.get(0);
                String payResult=detail.getStr("payResult");
                String payAmount=detail.getStr("payAmount");

                //调用订单的处理方法(异步通知.)
                payService.handLeKuaiQianNotify(orderId,payResult,payAmount);
            }
            //把处理后的订单删除
            payService.removeOrderIdRedis(orderId);
        }
    }
}
